package com.share.starter.sharding.rule;

import io.shardingsphere.api.algorithm.sharding.ListShardingValue;
import io.shardingsphere.api.algorithm.sharding.ShardingValue;
import io.shardingsphere.api.algorithm.sharding.complex.ComplexKeysShardingAlgorithm;

import java.util.Collection;
import java.util.LinkedHashSet;

/**
 * @author syq
 * @data 2019/6/27
 */
@SuppressWarnings("unchecked")
public class StringComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm {
    private int dbNum;
    private int tabNum;

    public StringComplexKeysShardingAlgorithm(int dbNum,int tabNum){
        this.dbNum = dbNum;
        this.tabNum = tabNum;
    }
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames,
                                         Collection<ShardingValue> shardingValues) {
        Collection<String> result = new LinkedHashSet<>();
        Long value = null;
        for (ShardingValue shardingValue : shardingValues) {
            if (shardingValue.getClass().getName().equals(ListShardingValue.class.getName())) {
                ListShardingValue<Long> listShardingValue = (ListShardingValue<Long>) shardingValue;
                Collection<Long> listValues = listShardingValue.getValues();
                for (Long orderId : listValues) {
                    value = orderId;
                    break;
                }
            }
        }
        int index = Math.abs(value.hashCode()) % availableTargetNames.size();
        int i = 0;
        for (String tableName : availableTargetNames) {
            if (i == index) {
                result.add(tableName);
                break;
            }
            i++;
        }
        return result;
    }
}
